from django import forms
from .models import Student
from grades.models import Grade

from django.core.exceptions import ValidationError
import datetime


class StudentForm(forms.ModelForm):
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields.get('grade').queryset = Grade.objects.all().order_by('grade_number')

    # 自定义验证方法 在使用form表单时，可以自动匹配到clean_<字段名>，clean千万不能写错
    def clean_student_name(self):
        student_name = self.cleaned_data.get('student_name')
        if len(student_name) < 2:
            raise ValidationError('请填写正确姓名格式')
        return student_name

    def clean_student_number(self):
        student_number = self.cleaned_data.get('student_number')
        if len(student_number) != 9:
            raise ValidationError('学号必须为9位')
        if not student_number:
            raise ValidationError("学籍号不能为空")
        
        # 不能有这个 当我要更新数据就会报错了
        # if Student.objects.filter(student_number=student_number).exists():
        #     raise ValidationError("学籍号已存在") 
        
        return student_number
    
    def clean_birthday(self):
        birthday = self.cleaned_data.get('birthday')
        if not isinstance(birthday, datetime.date):
            raise ValidationError("出生日期格式不正确,请使用2026-04-01格式")
        if birthday > datetime.date.today():
            raise ValidationError("出生日期不能晚于今天")
        
        return birthday
    
    def clean_contact(self):
        contact = self.cleaned_data.get('contact')
        if len(contact) != 11 or not contact.isdigit():
            raise ValidationError("联系方式必须是11位数字")
        
        return contact

    class Meta:
        model = Student
        fields = ['student_number','student_name','grade','gender','birthday','contact','address']

    